import uuid
from django.db import models
from django.utils import timezone

from ..ProjectsManagement.models import Project


class Asset(models.Model):
    """资源表模型"""
    objects = models.Manager()

    TYPE_CHOICES = [
        ('background', '背景'),
        ('mask', '蒙版'),
        ('font', '字体')
    ]

    id = models.CharField(primary_key=True, default=uuid.uuid4, max_length=255, editable=False,
                          verbose_name="资源唯一标识")
    project = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="assets", verbose_name="关联项目")
    type = models.CharField(max_length=20, choices=TYPE_CHOICES, verbose_name="资源类型(background/mask/font)")
    url = models.CharField(max_length=500, verbose_name="资源URL")
    original_filename = models.CharField(max_length=255, verbose_name="原始文件名")
    file_size = models.IntegerField(verbose_name="文件大小(字节)")
    mime_type = models.CharField(max_length=100, verbose_name="MIME类型")
    width = models.IntegerField(null=True, blank=True, verbose_name="图片宽度")
    height = models.IntegerField(null=True, blank=True, verbose_name="图片高度")
    thumbnail_url = models.CharField(null=True, blank=True, max_length=500, verbose_name="缩略图URL")
    optimized_url = models.CharField(null=True, blank=True, max_length=500, verbose_name="优化后的URL")
    created_at = models.DateTimeField(default=timezone.now, db_index=True, verbose_name="创建时间")

    class Meta:
        db_table = 'assets'
        verbose_name = '资源'
        verbose_name_plural = '资源'

    def __str__(self):
        return f"{self.original_filename}"

    def save(self, *args, **kwargs):
        if self.type not in ['background', 'mask']:
            self.width = None
            self.height = None
        super().save(*args, **kwargs)
